Lesson 1: Java Basics
1. Variables and Data Types
What are Variables?
Variables are containers used to store data.
- In Java, every variable has a type that defines the kind of data it can hold.
Common Data Types in Java:
Data Type | Size | Description | Example |
---|---|---|---|
int | 4 bytes | Stores integers | int age = 25; |
double | 8 bytes | Stores decimals | double price = 19.99; |
char | 2 bytes | Stores single characters | char grade = 'A'; |
String | Varies | Stores a sequence of characters | String name = "John"; |
boolean | 1 bit | Stores true or false values | boolean isActive = true; |
Code Example: Variables and Data Types
public class VariablesExample {
public static void main(String[] args) {
int age = 25; // Integer
double price = 19.99; // Decimal
char grade = 'A'; // Single character
String name = "John"; // String
boolean isActive = true; // Boolean
System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Grade: " + grade);
System.out.println("Name: " + name);
System.out.println("Active: " + isActive);
}
}
Expected Output:
Age: 25
Price: 19.99
Grade: A
Name: John
Active: true
2. Operators
Types of Operators in Java:
Operator | Description | Example |
---|---|---|
Arithmetic | Performs basic math | + , - , * , / , % |
Relational | Compares two values | < , > , <= , >= , == |
Logical | Combines boolean conditions | && , ` |
Assignment | Assigns values to variables | = , += , -= , etc. |
Code Example: Operators
public class OperatorsExample {
public static void main(String[] args) {
int a = 10, b = 20;
// Arithmetic Operators
int sum = a + b;
int diff = b - a;
// Relational Operators
boolean isGreater = b > a;
// Logical Operators
boolean andCondition = (a < b) && (b > 15);
System.out.println("Sum: " + sum);
System.out.println("Difference: " + diff);
System.out.println("Is b greater than a? " + isGreater);
System.out.println("Logical AND Condition: " + andCondition);
}
}
Expected Output:
Sum: 30
Difference: 10
Is b greater than a? true
Logical AND Condition: true
3. Input/Output
Taking Input from the User:
We use the Scanner
class in Java to get input from the user.
Code Example: Input/Output
import java.util.Scanner; // Import Scanner class
public class InputOutputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create Scanner object
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Read a String input
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Read an integer input
System.out.println("Hello " + name + ", you are " + age + " years old.");
}
}
Steps in NetBeans:
- Create a new Java file named
InputOutputExample
. - Copy and paste the code above.
- Run the program and interact with the console.
Sample Console Interaction:
Enter your name: John
Enter your age: 25
Hello John, you are 25 years old.